package com.blueberry.quiz_master.quiz.service;

import com.blueberry.quiz_master.quiz.model.QuestionBankRequest;
import com.blueberry.quiz_master.quiz.model.QuestionBankResponse;
import com.blueberry.quiz_master.redis.RedisService;
import com.blueberry.quiz_master.task.TaskService;
import com.blueberry.quiz_master.task.TaskStatus;
import com.blueberry.quiz_master.quiz.app.QuestionApp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class QuestionAsyncService {
    @Autowired
    private QuestionApp questionApp;
    @Autowired
    private RedisService redisService;
    @Autowired
    private TaskService taskService;  // 依赖任务管理服务

    /**
     * 异步生成题库（耗时操作）
     */
    @Async("taskExecutor")  // 引用线程池
    public void generateQuestionBankAsync(String taskId, QuestionBankRequest request) {
        try {
            // 步骤1：更新任务状态为“处理中”
            taskService.updateTaskStatus(taskId, TaskStatus.PROCESSING, null, null, null);

            // 步骤2：执行具体的题库生成逻辑（核心业务）
            QuestionBankResponse bank = doGenerateQuestionBank(request);  // 实际生成逻辑

            // 步骤3：生成成功，更新状态和结果地址
            String resultUrl = "/api/question-bank/" + bank.getId();  // 题库详情地址
            taskService.updateTaskStatus(taskId, TaskStatus.SUCCESS, bank.getId(), resultUrl, null);

        } catch (Exception e) {
            // 步骤4：生成失败，更新错误信息
            taskService.updateTaskStatus(taskId, TaskStatus.FAILED, null, null, e.getMessage());
        }
    }

    /**
     * 具体的题库生成逻辑（核心业务实现）
     */
    private QuestionBankResponse doGenerateQuestionBank(QuestionBankRequest request) {
        var response = questionApp.generateQuestionBank(request);
        redisService.setObject(response.getId(), response, 24, TimeUnit.HOURS);

        return response;
    }
}
